package com.lgp;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.logging.Logger;

/**
 * Created by lgp on 2017/7/6.
 */
@ServerEndpoint(value="/websocket/{relationId}")
public class Websocket {

	private static Logger logger = Logger.getLogger("lgp");

	/**
	 * 打开连接时触发
	 *
	 * @param relationId  唯一id
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("relationId") String relationId, Session session) {
		logger.info("Websocket 开始连接:" + SessionUtils.getKey(relationId));
		SessionUtils.put(relationId, session);
	}

	/**
	 * 收到客户端消息时触发
	 *
	 * @param relationId
	 * @param message
	 * @return
	 */
	@OnMessage
	public void onMessage(@PathParam("relationId") String relationId, String message) {

		SessionUtils.sendMessage("相客户端发送消息");  //可在程序中任意地方使用

	}

	/**
	 * 异常时触发
	 *
	 * @param relationId
	 * @param session
	 */
	@OnError
	public void onError(@PathParam("relationId") String relationId, Throwable throwable, Session session) {
		logger.info("Websocket 连接异常:" + SessionUtils.getKey(relationId));
		SessionUtils.remove(relationId);
	}

	/**
	 * 关闭连接时触发
	 *
	 * @param relationId
	 * @param session
	 */
	@OnClose
	public void onClose(@PathParam("relationId") String relationId, Session session) {
		logger.info("Websocket 关闭连接:" + SessionUtils.getKey(relationId));
		SessionUtils.remove(relationId);
	}
}
